package com.zf.yichat.utils.weixin;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zf.yichat.utils.common.OKHttpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;


/**
 * 公众平台通用接口工具类
 */
public class MyWeixinUtil {
    private static Logger logger = LoggerFactory.getLogger(MyWeixinUtil.class);

    private final static String APPID = "wx87375f86153f5101";
    private final static String SECRET = "9e290adeca6c07854d468592984fd650";
    // 获取登录鉴权的access_token
    private final static String AUTH_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
    //用户信息
    private final static String USER_INFO_URL = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID";
    // 获取调用接口的access_token的接口地址（GET） 限200（次/天）
    private final static String API_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
    private final static String JSAPI_TICKETE_URL = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi";

    // 菜单创建（POST） 限100（次/天）
    public static String menu_create_url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN";

    /**
     * 获取微信用户信息
     *
     * @param code
     * @return
     */
    public static String getUserInfo(String code) {
        String requestUrl = AUTH_ACCESS_TOKEN_URL.replace("APPID", APPID).replace("SECRET", SECRET).replace("CODE", code);
        String res = OKHttpUtil.httpGet(requestUrl);

        logger.debug("请求获取token返回：{}", res);
        String token = JSON.parseObject(res).getString("access_token");
        String openId = JSON.parseObject(res).getString("openid");

        String infoUrl = USER_INFO_URL.replace("ACCESS_TOKEN", token).replace("OPENID", openId);
        String infoRes = OKHttpUtil.httpGet(infoUrl);
        logger.debug("请求获取userinfo返回：{}", infoRes);
        return infoRes;
    }

    /**
     * 获取普通access_token
     *
     * @return
     */
    public static AccessToken getAccessToken() {
        AccessToken accessToken = null;

        String requestUrl = API_ACCESS_TOKEN_URL.replace("APPID", APPID).replace("APPSECRET", SECRET);

        String res = OKHttpUtil.httpGet(requestUrl);
        JSONObject jsonObject = JSON.parseObject(res);
        // 如果请求成功
        if (null != jsonObject && jsonObject.getString("access_token") != null) {
            accessToken = new AccessToken();
            accessToken.setToken(jsonObject.getString("access_token"));
            accessToken.setExpiresIn(jsonObject.getIntValue("expires_in"));
        } else {
            logger.error("get access_token fail:", res);
        }
        return accessToken;
    }

    public static String getTicket(String accessToken) {
        String requestUrl = JSAPI_TICKETE_URL.replace("ACCESS_TOKEN", accessToken);
        String res = OKHttpUtil.httpGet(requestUrl);
        JSONObject jsonObject = JSON.parseObject(res);
        return (String) jsonObject.get("ticket");
    }

    public static Map<String, String> sign(String jsapiTicket, String url) {
        Map<String, String> ret = new HashMap<>();
        String nonce_str = create_nonce_str();
        String timestamp = create_timestamp();
        String string1;
        String signature = "";

        //注意这里参数名必须全部小写，且必须有序
        string1 = "jsapi_ticket=" + jsapiTicket +
                "&noncestr=" + nonce_str +
                "&timestamp=" + timestamp +
                "&url=" + url;
        System.out.println(string1);
        try {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(string1.getBytes("UTF-8"));
            signature = byteToHex(crypt.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        ret.put("url", url);
        ret.put("nonceStr", nonce_str);
        ret.put("timestamp", timestamp);
        ret.put("signature", signature);
        ret.put("appId", APPID);
        return ret;
    }

    public static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash) {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }

    public static String create_nonce_str() {
        return UUID.randomUUID().toString();
    }

    public static String create_timestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }
}
